package com.springSecurity.demo;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

/**
 * @author mol
 * @Date: 2018-01-06
 * @des: SpringSecurity配置文件
 */
@Configuration
@EnableWebSecurity
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter{
    @Autowired
    private MyUserSeervice userSeervice;
    /**
     * 忽略拦截静态文件
     * @param web
     * @throws Exception
     */
    @Override
    public void configure(WebSecurity web) throws Exception {
       web.ignoring().antMatchers("/js/**","/css/**","/images/**");
    }

    /**
     * 定义那些请求被处理方法以及那些请求被SpringSercurity拦截
     * @param http
     * @throws Exception
     */
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                //放行项目主路径
                .antMatchers("/").permitAll()
                //其余请求经过验证
                .anyRequest().permitAll()
                .and()
                //注销放行
                .logout().permitAll()
                .and()
                //登录放行
                .formLogin();
        http.csrf().disable();
        super.configure(http);
    }
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        /**
         * 制定一个用户，病定义角色为ADMIN
         *
        auth.inMemoryAuthentication().withUser("admin").password("123456").roles("ADMIN");
         * 制定一个用户，病定义角色为USER
        auth.inMemoryAuthentication().withUser("demo").password("demo").roles("USER");
         */
        auth.userDetailsService(userSeervice).passwordEncoder(new MyPasswordEncode());
        auth.jdbcAuthentication().usersByUsernameQuery("").authoritiesByUsernameQuery("").passwordEncoder(new MyPasswordEncode());
    }
}
